package com.itheima.health.mobile.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.mobile.utils.SMSUtils;
import com.itheima.health.mobile.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * @Author likepei
 * @Date 2020/1/30 21:15
 * @Version v1.0
 * @Description 短信验证码控制器
 */
@RestController
@RequestMapping("/mobile/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;

    /**
     * 手机快速登录时发送短信验证码
     * 步骤
     * 1.生成短信验证码
     * 2.调用三方发送短信验证码
     * 3.把验证码缓存到redis
     *
     * @param telephone 手机号码
     */
    @RequestMapping("/send4Login")
    public Result send4Login(String telephone){
        try {
            //生成6位短信验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            //调用三方发送短信验证码
            //SMSUtils.sendShortMessage(telephone, code.toString());
            System.out.println("发送的手机验证码为code = " + code);
            //把验证码换成到redis
            jedisPool.getResource().setex(telephone + RedisConst.SENDTYPE_LOGIN, 5 * 60, code.toString());
            //返回, 发送验证码成功
            return new Result(true, MessageConst.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            //返回, 发送验证码失败
            return new Result(false, MessageConst.SEND_VALIDATECODE_FAIL);
        }
    }

    /**
     * 手机体检预约时发送短信验证码
     * 步骤
     * 1.生成短信验证码
     * 2.调用三方发送短信验证码
     * 3.把验证码缓存到redis
     *
     * @param telephone 手机号码
     */
    @RequestMapping("/send4Order")
    public Result send4Order(String telephone){
        try {
            //生成短信验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            //调用三方发送短信验证码
            //SMSUtils.sendShortMessage(telephone, code.toString());
            System.out.println("发送的手机验证码为code = " + code);
            //把验证码换成到redis
            jedisPool.getResource().setex(telephone + RedisConst.SENDTYPE_ORDER, 5 * 60, code.toString());
            //返回, 发送验证码成功
            return new Result(true, MessageConst.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            //返回, 发送验证码失败
            return new Result(false, MessageConst.SEND_VALIDATECODE_FAIL);
        }
    }
}
